package com.hns.can.mainte.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.hns.can.common.vo.SysCacheVo;
import com.hns.can.master.entity.BaseEqmtInfoEntity;
import com.hns.can.master.upgrade.UpgradeProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.aop.orgTree.LeftOrgAnnotation;
import com.hns.can.common.constants.GlobalConst;
import com.hns.can.common.formula.FillCodeDscValue;
import com.hns.can.common.formula.FillParamsVo;
import com.hns.can.mainte.entity.UpgEqmtVrsnManageInfo;
import com.hns.can.mainte.entity.UpgEqmtVrsnManageLog;
import com.hns.can.mainte.vo.UpgradeVo;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.service.CommonService;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.SearchConditionVo;
import com.hns.tool.pub.UtilString;

/**
 * 空调Service
 * @author:zhangzq
 * @email:
 * @version Revision 2.0.0
 */
@Service
public class AirConditionerService extends CommonService{

    @Autowired
    private TaskExecutor taskExecutor;
	
    @Autowired
    private FillCodeDscValue codeDscValue;
	
	/**
	 * 新增空调模版
	 * @param entity 空调模版
	 * @param user 用户
	 * @return
	 * @throws Exception
	 * @author:zhangzq
	 * @email:
	 */
	@Transactional
    public void addAirTemplate(UpgEqmtVrsnManageInfo entity,SysUserEntity user) throws Exception{
		String corpId = user.getCorpId();
        entity.setCorpId(corpId);
        entity.setVrsnId(UtilString.getUUID());
        //空调-版本类型
        //entity.setVrsnType("VERS0007");
        //上传日期
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        entity.setUploadDate(df.format(new Date()));        
        entity.setCrtTime(new Date());
        entity.setCrtUser(user.getAcctName());
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());        
        //版本名称唯一性
        Integer count = (Integer) sqlMapDao.selectOne("airConditioner.checkVrsnName", entity);
        if(count > 0){
        	throw new BusinessException(MsgType.WARN.getFlag(), "您输入的版本名称已经存在。");
        }
        commonEntityDao.save(entity);
	}
	
	/**
	 * 删除空调模版
	 * @param vrsnId 空调模版Id
	 * @author:zhangzq
	 * @email:
	 */
    @Transactional
    public void delAirTemplate(String vrsnId) throws Exception{
        UpgEqmtVrsnManageInfo entity = commonEntityDao.find(vrsnId, UpgEqmtVrsnManageInfo.class);
        commonEntityDao.delete(entity);
    }
	
	/**
	 * 更新空调模版
	 * @param entity 空调模版实体
	 * @param user 用户
	 * @author:zhangzq
	 * @email:
	 */
	@Transactional
    public void updateAirTemplate(UpgEqmtVrsnManageInfo entity,SysUserEntity user) throws Exception{
		UpgEqmtVrsnManageInfo origEntity = commonEntityDao.find(entity.getVrsnId(), UpgEqmtVrsnManageInfo.class);
		String corpId = user.getCorpId();
        entity.setCorpId(corpId);
        if(!origEntity.getVrsnName().equals(entity.getVrsnName())){
	    	//版本名称唯一性
	        Integer count = (Integer) sqlMapDao.selectOne("airConditioner.checkVrsnName", entity);
	        if(count > 0){
	        	throw new BusinessException(MsgType.WARN.getFlag(), "您输入的版本名称已经存在。");
	        }
        }
        origEntity.setCorpId(corpId);
        origEntity.setUpdateTime(new Date());
        origEntity.setUpdateUser(user.getAcctName());
        origEntity.setVrsnName(entity.getVrsnName());
        origEntity.setAirCondiEffectBeginDate(entity.getAirCondiEffectBeginDate());
        origEntity.setAirCondiEffectEndDate(entity.getAirCondiEffectEndDate());
        origEntity.setAirCondiEffectBeginTime(entity.getAirCondiEffectBeginTime());
        origEntity.setAirCondiEffectEndTime(entity.getAirCondiEffectEndTime());
        origEntity.setAcSt(entity.getAcSt());
        origEntity.setAirCondiStmOprtSt(entity.getAirCondiStmOprtSt());
        origEntity.setAirCondiStmFanOprtSt(entity.getAirCondiStmFanOprtSt());
        origEntity.setAirCondiHighestTept(entity.getAirCondiHighestTept());
        origEntity.setAirCondiLowestTept(entity.getAirCondiLowestTept());
        origEntity.setFreshAirOpenTime(entity.getFreshAirOpenTime());
        origEntity.setFreshAirCloseTime(entity.getFreshAirCloseTime());
        origEntity.setClockCtrl(entity.getClockCtrl());
        commonEntityDao.update(origEntity);
	}
	
	/**
	 * 获取空调模版
	 * @param vrsnId 空调模版Id
	 * @return
	 * @author:zhangzq
	 * @email:
	 */
    @Transactional
    public UpgEqmtVrsnManageInfo getAirTemplateById(String vrsnId) throws Exception{
        UpgEqmtVrsnManageInfo entity = commonEntityDao.find(vrsnId, UpgEqmtVrsnManageInfo.class);
        return entity;
    }
    
    /**
     * 分页查询空调设置
     * @param paramMap 查询参数map
     * @param user 用户
     * @return
     * @author:zhangzq
     * @email:
     */
    @Transactional
    public Pagination searchAirSetPage(Map<String, Object> paramMap,SysUserEntity user)  throws Exception{
        String corpId = user.getCorpId();
        paramMap.put("corpId", corpId);
        Pagination page = this.myBatisPage("airConditioner.getAirSetCnt", "airConditioner.getAirSetList", paramMap, UpgEqmtVrsnManageInfo.class);
        return page;
    }
	
    @SuppressWarnings("static-access")
	@LeftOrgAnnotation()
    @Transactional
    public Pagination searchAirTemplateMonitor(UpgradeVo vo) throws Exception {        
        Pagination page = this.myBatisPage("airConditioner.searchAirTemplateMonitorCount", "airConditioner.searchAirTemplateMonitorList", vo, UpgEqmtVrsnManageInfo.class);
        List list = page.getData();
        Map<String,String> map = new HashMap<String,String>();
        map.put("vrsnName",  GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo1 = new FillParamsVo("vrsnId", map);
        map = new HashMap<String,String>();
        map.put("licPltNo",  GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo2 = new FillParamsVo("carId", map);
        codeDscValue.fillInfoValue(list,new String[]{GlobalConst.CACHE_KEY_UPG_EQMT_VRSN_MANAGE_INFO,GlobalConst.CACHE_KEY_BASE_CAR_INFO},vo1,vo2);
        page.setData(list);
        return page;
    }
    
    /**
     * 
     * @param entity
     * @return
     * @author:zhangzq
     * @email:
     */
    @SuppressWarnings("unchecked")
	@Transactional
    public  List<UpgEqmtVrsnManageInfo>  getVersionName(UpgEqmtVrsnManageInfo entity) throws Exception {
        List<UpgEqmtVrsnManageInfo> list = PubUtil.convertListMapToObject(sqlMapDao.selectList("airConditioner.getVersionName", entity), UpgEqmtVrsnManageInfo.class);
        return list;
    }
    
    /**
     * 分页查询空调参数下发日志
     * @param conditionVo
     * @return
     * @throws Exception
     * @author:zhangzq
     * @email:
     */
    @SuppressWarnings("static-access")
	@LeftOrgAnnotation()
    @Transactional
    public Pagination searchAppUpgLogPage(SearchConditionVo conditionVo) throws Exception {
        Pagination page = this.myBatisPage("appUpgrade.getAppUpgLogCnt", "appUpgrade.getAppUpgLogList", conditionVo, UpgEqmtVrsnManageLog.class);
        List list = page.getData();
        Map<String,String> map = new HashMap<String,String>();
        map.put("licPltNo", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo1 = new FillParamsVo("carId", map);
        map = new HashMap<String,String>();
        map.put("lineName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo2 = new FillParamsVo("lineId", map);
        map = new HashMap<String,String>();
        map.put("eqmtCd", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo3 = new FillParamsVo("eqmtId", map);
        codeDscValue.fillInfoValue(list,new String[]{GlobalConst.CACHE_KEY_BASE_CAR_INFO,GlobalConst.CACHE_KEY_BASE_LINE_INFO,GlobalConst.CACHE_KEY_BASE_EQMT_INFO},vo1,vo2,vo3);
        page.setData(list);
        return page;
    }

    @Transactional
    public Object getTCommMftCopaAir() throws Exception {
        Map<String, List<SysCacheVo>> result = new HashMap<String, List<SysCacheVo>>();
        List<SysCacheVo> list = PubUtil.convertListMapToObject(sqlMapDao.selectList("airConditioner.getTCommMftCopaAir", null), SysCacheVo.class);
        if(PubUtil.isNotEmpty(list)){
            for (SysCacheVo entity : list) {
                String code = entity.getCodeClId();
                List<SysCacheVo> temp = result.get(code);
                if(temp == null){
                    temp = new ArrayList<SysCacheVo>();
                    result.put(code, temp);
                }
                temp.add(entity);
            }
        }
        return result;
    }

    @Transactional
    public void templateAirConditioIssued(UpgEqmtVrsnManageInfo entity,SearchConditionVo vo)throws Exception {
        addAirTemplate(entity,this.getCurrentUser().getUser());
        SysUserEntity user = this.getCurrentUser().getUser();
        SimpleDateFormat  sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(String carId : vo.getOrgIds()){
            String eqmtId="";
            String eqmtCd="";
            String corpId="";
            List list  =commonEntityDao.findByJpql("from BaseEqmtInfoEntity m where rltvCarId=?1 and enabledSt=?2",new Object[]{carId,"1"});
            if(PubUtil.isNotEmpty(list)){
                BaseEqmtInfoEntity obj=(BaseEqmtInfoEntity)list.get(0);
                eqmtCd=obj.getEqmtCd();
                eqmtId=obj.getEqmtId();
                corpId=obj.getCorpId();
            }
            //新增日志
            UpgEqmtVrsnManageLog logEntity = new UpgEqmtVrsnManageLog();
            logEntity.setLogId(UtilString.getUUID());
            logEntity.setLogType("ULOG0009");
            logEntity.setCorpId(corpId);
            logEntity.setEqmtId(eqmtId);
            logEntity.setCarId(carId);
            logEntity.setVrsnId(entity.getVrsnId());
            logEntity.setUpgradeBeginTime(sd.format(new Date()));
            logEntity.setUpgradeSt("UPST0200");
            logEntity.setStMsg("UPSM0101");
            logEntity.setUpgradeUser(user.getAcctName());
            commonEntityDao.save(logEntity);
            //开启后台升级进程
            String upgradeCommandStr="";
            if(entity.getVrsnType().equals("VERS0007")){
                upgradeCommandStr = "{'devId': '"+ eqmtCd +"','canId': '17', 'ac':'"+entity.getAcSt()+"','operateStatus':'"+ entity.getAirCondiStmOprtSt() +"','fanStatus': '"+ entity.getAirCondiStmFanOprtSt() +"','minTemp': '"+ entity.getAirCondiLowestTept() +"','maxTemp': '"+ entity.getAirCondiHighestTept() +"'}";
            }
            else if(entity.getVrsnType().equals("VERS0008")){
                upgradeCommandStr = "{'devId': '"+ eqmtCd +"','canId': '17','paramId': '241', 'evaporateGears':'"+entity.getAirCondiStmFanOprtSt()+"','setTemp':'"+ entity.getAirCondiLowestTept() +"','ac': '"+ entity.getAcSt() +"','operateStatus': '"+ entity.getAirCondiStmOprtSt() +"','freshOpenTime': '"+ entity.getFreshAirOpenTime()+"','freshCloseTime': '"+ entity.getFreshAirCloseTime()+"','lockStatus': '"+ entity.getClockCtrl() +"'}";
            }
            else if(entity.getVrsnType().equals("VERS0009")){
                upgradeCommandStr = "{'devId': '"+ eqmtCd +"','canId': '17','paramId': '241', 'evaporateGears':'"+entity.getAirCondiStmFanOprtSt()+"','teptLimitDw': '"+ entity.getAirCondiLowestTept() +"','teptLimitUp': '"+ entity.getAirCondiHighestTept() +"','ac': '"+ entity.getAcSt() +"','operateStatus': '"+ entity.getAirCondiStmOprtSt() +"','freshOpenTime': '"+ entity.getFreshAirOpenTime()+"','freshCloseTime': '"+ entity.getFreshAirCloseTime()+"','lockStatus': '"+ entity.getClockCtrl() +"'}";
            }
            UpgradeProcessor processor = new UpgradeProcessor("17", upgradeCommandStr, taskExecutor);
            processor.process();
        }
    }
}
